package com.villaday.idf.activity;

import androidx.appcompat.widget.Toolbar;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.villaday.idf.R;
import com.villaday.idf.base.BaseActivity;
import com.villaday.idf.base.BaseDialog;
import com.villaday.idf.custom.LoadingDialog;
import com.villaday.idf.custom.PayDialog;
import com.villaday.idf.model.PayEntity;
import com.villaday.idf.model.PayMent;
import com.villaday.idf.model.PayOrders;
import com.villaday.idf.model.PayOrdersEntity;
import com.villaday.idf.model.RefreshtokenEntity;
import com.villaday.idf.util.Constant;
import com.villaday.idf.util.LogeUtil;
import com.villaday.idf.util.OkHttpUtil;
import com.villaday.idf.util.SharedPreferencesUtil;
import com.villaday.idf.util.ToastUtil;
import com.villaday.idf.util.ToolBarUtil;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/*

????
* */
public class PayOrderActivity extends BaseActivity implements OkHttpUtil.OnDataListener {


    @BindView(R.id.toolbar_text)
    Toolbar toolbarText;
    @BindView(R.id.sdv)
    SimpleDraweeView sdv;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_detail)
    TextView tvDetail;
    @BindView(R.id.tv_date)
    TextView tvDate;
    @BindView(R.id.et_name)
    TextView etName;
    @BindView(R.id.et_phone)
    TextView etPhone;
    @BindView(R.id.tv_yuanjia)
    TextView tvYuanjia;
    @BindView(R.id.tv_shoujia)
    TextView tvShoujia;
    @BindView(R.id.tv_youhui)
    TextView tvYouhui;

    @BindView(R.id.tv_useyue)
    TextView tvUseyue;
    @BindView(R.id.tv_pay_sign)
    TextView tvPaySign;
    @BindView(R.id.tv_pay_num)
    TextView tvPayNum;

    @BindView(R.id.tv_useyueNum)
    TextView tvUseyueNum;
    @BindView(R.id.tv_confirm)
    TextView tvConfirm;
    @BindView(R.id.ll_yue)
    LinearLayout llYue;

    @BindView(R.id.ll_date)
    LinearLayout llDate;

    @BindView(R.id.ll_youhui)
    LinearLayout llYouhui;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.tv_num)
    TextView tvNum;

    @BindView(R.id.ll_price)
    LinearLayout llPrice;

    @BindView(R.id.ll_nameAndPhone)
    LinearLayout ll_nameAndPhone;
    @BindView(R.id.ll_addr)
    LinearLayout llAddr;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.tv_addr)
    TextView tvAddr;

    @BindView(R.id.ll_email)
    LinearLayout llEmail;
    @BindView(R.id.tv_email)
    TextView tvEmail;

    @BindView(R.id.ll_idCard)
    LinearLayout llIdCard;
    @BindView(R.id.tv_idCard)
    TextView tvIdCard;

    @BindView(R.id.ll_LianZhuYouhui)
    LinearLayout llLianZhuYouhui;
    @BindView(R.id.tv_LianZhuYouhui)
    TextView tvLianZhuYouhui;

    @BindView(R.id.ll_yajin)
    LinearLayout llYajin;
    @BindView(R.id.tv_yajin)
    TextView tvYajin;

    @BindView(R.id.textView8)
    TextView textView8;

    @BindView(R.id.ll_yuanjia)
    LinearLayout llYuanjia;
    @BindView(R.id.tv_remarks)
    TextView tvRemarks;
    @BindView(R.id.ll_remarks)
    LinearLayout llRemarks;

    @BindView(R.id.ll_datefortemai)
    LinearLayout ll_datefortemai;

    @BindView(R.id.tv_datefortemai)
    TextView tv_datefortemai;


    private Gson gson = new GsonBuilder().create();
    private PayOrders.ProductEntity productEntity;
    private PayOrders toJson;
    private String in;
    private String out;
    private PayOrdersEntity ordersPrepare;
    private LoadingDialog loadingDialog;
    private int quantity;
    private PayEntity payEntity;


    @Override
    protected int getViewResId() {
        return R.layout.activity_pay_order;
    }

    @Override
    protected void init() {
        boolean allowSelectDate = getIntent().getBooleanExtra("allowSelectDate", false);
        if (allowSelectDate) {
            ll_datefortemai.setVisibility(View.VISIBLE);
            tv_datefortemai.setText(getIntent().getStringExtra("checkInDate"));
        } else {
            ll_datefortemai.setVisibility(View.GONE);

        }

        boolean hasHouse = getIntent().getBooleanExtra("hasHouse", true);
        if (hasHouse) {

        } else {//多店通用
            tvDetail.setVisibility(View.GONE);
        }


        if (getIntent().getIntExtra("type", 0) == 0) {//房源类型
            llYuanjia.setVisibility(View.VISIBLE);
        } else {
            llYuanjia.setVisibility(View.GONE);

        }


        if (getIntent().getBooleanExtra("AllowAddress", false)) {
            String Name = getIntent().getStringExtra("tvName");
            String Phone = getIntent().getStringExtra("tvPhone");
            String Addr = getIntent().getStringExtra("tvAddr");


            tvName.setText(Name);
            tvPhone.setText(Phone);
            tvAddr.setText(Addr);
            llAddr.setVisibility(View.VISIBLE);
            ll_nameAndPhone.setVisibility(View.GONE);
        }

        if (!TextUtils.isEmpty(getIntent().getStringExtra("remarks"))) {
            llRemarks.setVisibility(View.VISIBLE);
            tvRemarks.setText(getIntent().getStringExtra("remarks"));
        }
        ToolBarUtil.initToolBar(toolbarText, "支付订单", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        RefreshtokenEntity.BodyBean roleInfo =
                SharedPreferencesUtil.getRoleInfo(this);
        String roleType = roleInfo.getMember().getType();
        if ("0".equals(roleType)) {
            llYue.setVisibility(View.GONE);
        } else {
            llYue.setVisibility(View.GONE);
            llYue.setVisibility(View.VISIBLE);

        }
        quantity = getIntent().getIntExtra("quantity", 1);
    }

    @Override
    protected void loadData() {
        String dataEntity = getIntent().getStringExtra("dataEntity");

        ordersPrepare = gson.fromJson(dataEntity, PayOrdersEntity.class);
        if ("200".equals(ordersPrepare.getCode())) {
            if (ordersPrepare.getBody() != null) {
                initData(ordersPrepare.getBody());
            }
        } else {
            ToastUtil.initToast(this, ordersPrepare.getMsg());
        }

       /* loadingDialog = LoadingDialog.newInstance("加载中");
        loadingDialog.show(getFragmentManager(), "loading");
        Map<String, Object> map = new HashMap<>();*/
        int type = getIntent().getIntExtra("type", 0);
        //map.put("type", type);
        if (type == 0) {
            String checkInDate = getIntent().getStringExtra("checkInDate");
            String checkOutDate = getIntent().getStringExtra("checkOutDate");
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat formatNew = new SimpleDateFormat("MM月dd日");
            try {
                in = formatNew.format(format.parse(checkInDate));
                out = formatNew.format(format.parse(checkOutDate));

            } catch (ParseException e) {
                e.printStackTrace();
            }
            tvDate.setText(in + "-" + out + "（" + getIntent().getIntExtra("nightNum", 0) + "晚）");

            llDate.setVisibility(View.VISIBLE);

            textView8.setText("房费");


            //productEntity = new PayOrders.ProductEntity(getIntent().getStringExtra("product_id"), getIntent().getIntExtra("product_type", 100), getIntent().getIntExtra("product_quantity", 1));
            // map.put("product", productEntity);

            //map.put("checkInDate", getIntent().getStringExtra("checkInDate"));
            // map.put("checkOutDate", getIntent().getStringExtra("checkOutDate"));

            /*intent.putExtra("type", getIntent().getIntExtra("type", 0));
            intent.putExtra("product_id", getIntent().getStringExtra("product_id"));
            intent.putExtra("product_type", getIntent().getIntExtra("product_type", 100));
            intent.putExtra("product_quantity", getIntent().getIntExtra("product_quantity", 1));
            intent.putExtra("checkInDate", getIntent().getStringExtra("checkInDate"));
            intent.putExtra("checkOutDate", getIntent().getStringExtra("checkOutDate"));

            intent.putExtra("mobile", etPhone.getText());
            intent.putExtra("linkman", etName.getText());
            intent.putExtra("useWallet", ordersPrepare.getBody().isAllowUseWallet());
            intent.putExtra("walletDeductibleAmount", ordersPrepare.getBody().getWalletDeductibleAmount());*/


            //toJson = new PayOrders(type, productEntity, getIntent().getStringExtra("checkInDate"), getIntent().getStringExtra("checkOutDate"), getIntent().getStringExtra("mobile"), getIntent().getStringExtra("linkman"), getIntent().getBooleanExtra("useWallet", false), getIntent().getLongExtra("walletDeductibleAmount", 0));

        } else if (type == 7) {
            // PayOrders.ActivityEntity activityEntity = new PayOrders.ActivityEntity(getIntent().getStringExtra("activity_id"), getIntent().getIntExtra("activity_type", 13), quantity);
            // toJson = new PayOrders(type, activityEntity, getIntent().getStringExtra("mobile"), getIntent().getStringExtra("linkman"), getIntent().getBooleanExtra("useWallet", false), getIntent().getLongExtra("walletDeductibleAmount", 0));

            llDate.setVisibility(View.GONE);
            tvPrice.setVisibility(View.VISIBLE);
            tvNum.setVisibility(View.VISIBLE);
            llPrice.setVisibility(View.VISIBLE);

            tvNum.setText("x" + quantity);
            textView8.setText("原价");

        }

        //OkHttpUtil.postJson(this, Constant.URL.orders, toJson, map, this);
    }

    @Override
    public void onResponse(String url, String json) {
        if (!TextUtils.isEmpty(json)) {
            if (Constant.URL.orders.equals(url)) {
                dismissLoading();
                LogeUtil.e("orders_prepare", json);

                ordersPrepare = gson.fromJson(json, PayOrdersEntity.class);
                if ("200".equals(ordersPrepare.getCode())) {
                    if (ordersPrepare.getBody() != null) {
                        initData(ordersPrepare.getBody());
                    }
                } else {
                    ToastUtil.initToast(this, ordersPrepare.getMsg());
                }
            }
        }
    }

    private void dismissLoading() {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }


    }

    private void initData(PayOrdersEntity.BodyEntity data) {

        if (TextUtils.isEmpty(data.getEmail())) {
            llEmail.setVisibility(View.GONE);
        } else {
            llEmail.setVisibility(View.VISIBLE);

            tvEmail.setText(ordersPrepare.getBody().getEmail());


        }
        if (TextUtils.isEmpty(data.getIdentityNumber())) {
            llIdCard.setVisibility(View.GONE);
        } else {
            llIdCard.setVisibility(View.VISIBLE);
            tvIdCard.setText(ordersPrepare.getBody().getIdentityNumber());

        }
        if (TextUtils.isEmpty(data.getStayDiscountAmountValue())) {
            llLianZhuYouhui.setVisibility(View.GONE);
        } else {
            llLianZhuYouhui.setVisibility(View.VISIBLE);
            tvLianZhuYouhui.setText("-" + data.getStayDiscountAmountValue());

        }
        if (data.getDepositType() == 0 && !TextUtils.isEmpty(data.getDepositAmountValue())) {
            llYajin.setVisibility(View.VISIBLE);
            tvYajin.setText("-" + data.getDepositAmountValue());

        } else {

            llYajin.setVisibility(View.GONE);
        }

        if (data.getDiscountAmount() > 0) {
            llYouhui.setVisibility(View.VISIBLE);
        } else {
            llYouhui.setVisibility(View.GONE);

        }
        if (data.getWalletDeductibleAmount() > 0) {
            llYue.setVisibility(View.VISIBLE);
        } else {
            llYue.setVisibility(View.GONE);

        }

        tvConfirm.setVisibility(data.isAllowPayment() ? View.VISIBLE : View.GONE);
        etName.setText(data.getLinkman());
        etPhone.setText(data.getMobile());

        sdv.setImageURI(data.getProduct().getImageUrl());
        tvTitle.setText(data.getProduct().getName() + "");
        if (data.getProduct().getDesc() == null) {
            tvDetail.setVisibility(View.GONE);
        }
        tvDetail.setText(data.getProduct().getDesc() + "");

        tvYuanjia.setText(Html.fromHtml("" + data.getOriginalPriceValue()));
        tvShoujia.setText(Html.fromHtml("&yen;" + data.getCurrentPriceValue()));
        tvYouhui.setText(Html.fromHtml("-" + data.getDiscountAmountValue()));
        tvUseyueNum.setText(Html.fromHtml("-" + data.getWalletDeductibleAmountValue()));
/*
        tvUseyue.setText(Html.fromHtml("&yen;" + PhoneUtil.handleBalance(data.getWalletBalance() / 100 + "", 2)));
*/
        tvPaySign.setText(Html.fromHtml("&yen;"));
        tvPayNum.setText(Html.fromHtml(data.getActualPriceValue()));
        tvPrice.setText(Html.fromHtml("&yen;" + data.getProduct().getCurrentPriceValue()));

    }

    @Override
    public void onFailure(String url, String error) {

    }


    @OnClick({R.id.tv_confirm})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.tv_confirm://??
                if (payEntity != null) {//再次支付
                    IWXAPI api = WXAPIFactory.createWXAPI(PayOrderActivity.this, Constant.ID.WeChat_APP_ID, true);
                    api.registerApp(Constant.ID.WeChat_APP_ID);
                    if (!api.isWXAppInstalled()) {//?????
                        ToastUtil.initToast(PayOrderActivity.this, "??????");
                        return;
                    }
                    PayEntity.BodyEntity body = payEntity.getBody();
                    PayReq req = new PayReq();
                    //req.appId = "wxf8b4f85f3a794e77";  // ??????appId
                    req.appId = body.getAppid();
                    req.partnerId = body.getPartnerid();
                    req.prepayId = body.getPrepayid();
                    req.nonceStr = body.getNoncestr();
                    req.timeStamp = body.getTimestamp();
                    req.packageValue = body.getPackageX();
                    req.sign = body.getSign();
                    req.extData = "app data";
                    // ?????????????????????????????????IWXMsg.registerApp???????????
                    api.sendReq(req);
                } else {//支付失败
                    if (ordersPrepare != null && ordersPrepare.getBody() != null) {
                        if (ordersPrepare.getBody().isAllowPayment()) {
                            final PayDialog payDialog = PayDialog.newInstance(ordersPrepare.getBody().getActualPriceValue());
                            payDialog.show(getFragmentManager());
                            payDialog.setOnItemClickListener(new BaseDialog.OnItemClickListener() {
                                @Override
                                public void onItemClick(View v) {
                                    Map<String, Object> objectObjectHashMap = new HashMap<>();
                                    OkHttpUtil.postJson(PayOrderActivity.this, Constant.URL.pay, new PayMent(ordersPrepare.getBody().getOrderNo(), 2), objectObjectHashMap, new OkHttpUtil.OnDataListener() {
                                        @Override
                                        public void onResponse(String url, String json) {

                                            if (!TextUtils.isEmpty(json)) {
                                                LogeUtil.e("pay11", json);
                                                SharedPreferencesUtil.saveWeOrderNum(PayOrderActivity.this, ordersPrepare.getBody().getOrderNo());
                                                payEntity = gson.fromJson(json, PayEntity.class);
                                                if ("200".equals(payEntity.getCode())) {
                                                    IWXAPI api = WXAPIFactory.createWXAPI(PayOrderActivity.this, Constant.ID.WeChat_APP_ID, true);
                                                    api.registerApp(Constant.ID.WeChat_APP_ID);
                                                    if (!api.isWXAppInstalled()) {//?????
                                                        ToastUtil.initToast(PayOrderActivity.this, "??????");
                                                        return;
                                                    }
                                                    PayEntity.BodyEntity body = payEntity.getBody();
                                                    PayReq req = new PayReq();
                                                    //req.appId = "wxf8b4f85f3a794e77";  // ??????appId
                                                    req.appId = body.getAppid();
                                                    req.partnerId = body.getPartnerid();
                                                    req.prepayId = body.getPrepayid();
                                                    req.nonceStr = body.getNoncestr();
                                                    req.timeStamp = body.getTimestamp();
                                                    req.packageValue = body.getPackageX();
                                                    req.sign = body.getSign();
                                                    req.extData = "app data";
                                                    // ?????????????????????????????????IWXMsg.registerApp???????????
                                                    api.sendReq(req);

                                                } else {
                                                    ToastUtil.initToast(PayOrderActivity.this, payEntity.getMsg());
                                                }


                                            }
                                        }

                                        @Override
                                        public void onFailure(String url, String error) {

                                        }
                                    });

                                }
                            });
                        }


                    }
                }


                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        //是否支付
        if (SharedPreferencesUtil.getWechatStatusForOrder(this)) {
            SharedPreferencesUtil.saveWechatStatusForOrder(this, false);

            onBackPressed();
        }
    }
}
